package com.lyb.springbootredisclient.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.shade.org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.lyb.springbootredisclient.app.impl.BpxhApprovalServiceFactory;
import com.lyb.springbootredisclient.app.sattagy.InsertSqlUtils;
import com.lyb.springbootredisclient.app.sattagy.LybService;
import com.lyb.springbootredisclient.config.InterfaceAutoConfiguration;
import com.lyb.springbootredisclient.entity.BpxhBizCommonRespDTO;
import com.lyb.springbootredisclient.entity.BpxhCommonCallbackDTO;
import com.lyb.springbootredisclient.entity.Result;
import com.lyb.springbootredisclient.entity.User;
import com.lyb.springbootredisclient.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.*;
import java.util.concurrent.Executor;

/**
 * @author: lyb  2022/7/2 23:02
 */
@Service
public class TestRedisServiceImpl  extends ApplicationObjectSupport implements TestRedisService {
    private static final Logger LOGGER = LoggerFactory.getLogger(TestRedisServiceImpl.class);
    @Resource
    ObjectMapper objectMapper;

    @Resource
    DataSourceTransactionManager transactionManager;

    @Resource
    private UserMapper userMapper;

    @Resource
    private LybService lybService;

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Autowired
    BpxhApprovalServiceFactory bpxhApprovalServiceFactory;

//    @Resource
//    private RedisTemplate redisTemplate;

//    @Resource
//    private ExecutorService taskExecutor;


    @Override
    public User userList(String processCategory) {
        BpxhCommonCallbackDTO bpxhCommonCallbackDTO = new BpxhCommonCallbackDTO();
        BpxhBizCommonRespDTO approval = bpxhApprovalServiceFactory.buildApprovalService(processCategory).approval(bpxhCommonCallbackDTO);
        System.out.println(approval.toString());
//        List<String> strings = Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "W", "R", "Y", "EE", "QQ");
////        // 执行业务逻辑,十秒
//        InsertSqlUtils.batchInsertData(ss-> {
//            try {
//                lybService.doServiceProcess(ss);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        }, strings, 4);
//        lybService.doServiceProcess(user);
//        BigDecimal decimal=null;
//        List<String> a = Arrays.asList("ll");
//        if (true) {
//            a.forEach(e->{
//                if ( user.getAge().compareTo(new BigDecimal(100))==1){
//                    System.out.println("KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK");
//                }
//              ;
//            });
//
//        }
        //获取线程池对象
//        Object bean = super.getApplicationContext().getBean("hzero-boot-interface-executor");
//        Executor executor = (Executor) bean;
//        executor.execute(() -> );

//        System.out.println(Thread.currentThread().getName());
//        User user  = userMapper.getUserById("A3");
//        try{
//            if (user.getUserName() == null || StringUtils.isEmpty(user.getUserCode()) && StringUtils.isEmpty(user.getEmail())) {
//                throw new RuntimeException();
//            }
//            String s = Optional.ofNullable(user.getEmail()).orElse("");
//            System.out.println("SSSSSSSSSSSSSSSSSSSSSS+"+s);
//            todo();
//        }catch (Exception e){
//            System.out.println("》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》");
//        }

        return new User();
    }

    private void todo() {
        String s= "lyb";
        if ("lyb".equals(s)) {
            throw new RuntimeException("测试报错");
        }
    }

    @Async("hzero-boot-interface-executor")
    public void doServiceProcess(User userCode) {


        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        LOGGER.info(";;;;;;;;;;;;;;;;;;;;;;;;;;;;;{}", userCode);
        LOGGER.info(";;;;;;;;;;;;;;;;;;;;;;;;;;;;;{}", Thread.currentThread().getName());
    }

    private void convert(Object user) {
        String s = JSON.toJSONString(user);
        JSONObject jo = new JSONObject();
        jo.put("paramsView" , s);
        String paramsView = jo.getString("paramsView");
        System.out.println(paramsView);
    }

    /**
     * 录入用户信息
     *
     * @param user 用户
     * @return User 用户列表
     */
    @Override

    public User userSyncRedis(User user) {

        try {

                Class.forName("com.mysql.jdbc.Driver");

            Connection  conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/todo?useUnicode=true&characterEncoding=utf-8&useSSL=false","root","root");

                conn.setAutoCommit(false);

            userMapper.insert(user);

            test(user);
            tes3(user);
            if (user != null) {
                throw new RuntimeException();
            }
            transactionManager.commit( transactionManager.getTransaction(new DefaultTransactionDefinition()));
        }catch (Exception e){
            e.printStackTrace();
            transactionManager.rollback( transactionManager.getTransaction(new DefaultTransactionDefinition()));
        }

        return user;
    }



    private void test(User user) {
        user.setUserName(user.getUserName()+"lyb");
        user.setId(user.getId()+1);
        userMapper.insert(user);
        test2(user);

    }

    private void test2(User user) {
        user.setUserName(user.getUserName()+"lyb");
        user.setId(user.getId()+1);
        userMapper.insert(user);
    }

    public void tes3(User user) {

        user.setUserName(user.getUserName()+"lyb3");
        user.setId(user.getId()+1);
        userMapper.insert(user);
    }

    /**
     * 插入50万条数据
     *
     * @param user 用户
     * @return User 用户列表
     */
    @Override
    public void insertManyData(User user) {
        List<User> userList = new ArrayList<>();
        for (int i = 0; i < 50; i++) {
            user.setId(Long.valueOf(i+1));
            user.setAge(new BigDecimal(i));
            user.setUserName(user.getUserName()+i);
            user.setUserName(user.getUserCode()+i);
            user.setEnabled(1);
            user.setEmail(1+"@qq.com");
            userList.add(user);
        }
        List<List<User>> partition = Lists.partition(userList, 500);
        for (List<User> users : partition) {
            System.out.println("分批后大小："+users.size());
        }

//        taskExecutor.execute(new AsyncInsertExecute(user,userMapper,userList));


    }
    public static String getLockKey(Object... objects) {
        return "price-lib-release." + StringUtils.joinWith(".", objects);
    }

//    public static void main(String[] args) {
//        String lockKey = getLockKey(21, 1, 2);
//        System.out.println(lockKey);
//    }
//    private void sdkInvoke() throws IOException {
//        // 请求参数
//        RequestBuilder requestBuilder = RequestBuilder.create(HttpMethod.GET.name());
//        // 初始化一个请求配置
//        RequestConfig.Builder builder = RequestConfig.custom();
//        // 配置连接时间以及请求时间
//        builder.setConnectTimeout(1000).setConnectionRequestTimeout(1000);
//        // 给请求设置一个请求地址和请求配置
//        requestBuilder.setUri("https://api.jisuapi.com/iqa/query").setConfig(builder.build());
//        // 构造请求头
//        this.generateRequestHeader(requestBuilder);
//        // 构造请求参数
//        this.generateRequestParam(requestBuilder);
//        // 构造请求体 省略
//
//        HttpUriRequest request = requestBuilder.build();
//        // 初始化一个http协议的请求客户端
//        HttpClientBuilder clientBuilder = HttpClients.custom();
//        clientBuilder.setConnectionManagerShared(true);
//        CloseableHttpClient closeableHttpClient = clientBuilder.build();
//        CloseableHttpResponse closeableHttpResponse = null;
//        try {
//            closeableHttpResponse = closeableHttpClient.execute(request);
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        // 再次处理响应
//        HttpEntity httpEntity = closeableHttpResponse.getEntity() == null ?
//                new StringEntity(StringUtils.EMPTY, StandardCharsets.UTF_8)
//                : closeableHttpResponse.getEntity();
//        // 字节输入流
//        InputStream inputStream = httpEntity.getContent();
//        // 字节输入流 读取成字节数组
//        byte[] bytes = IOUtils.toByteArray(inputStream);
//        // 把字节数组String类型
//        String responseContent = new String(bytes,StandardCharsets.UTF_8);
//        ResponseResult result = objectMapper.readValue(responseContent, ResponseResult.class);
//        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>"+result.getResult().getContent());
//        // 处理响应
//    }
//
//    private void syncRedis(List<User> user) throws JsonProcessingException {
//        String userKey = String.format("test:user:%d:%s", 21,"tatol");
//        Map<String,List<User>> h = new HashMap<>();
//        h.put("USER_LIST", user);
//        redisTemplate.opsForValue().set(userKey, JSONObject.toJSONString(h));
//
//        String str = (String) redisTemplate.opsForValue().get(userKey);
//        if (StringUtils.isNotBlank(str)) {
//            JSONObject responseObj = JSON.parseObject(str);
//            JSONArray user2 = responseObj.getJSONArray("USER_LIST");
//            List<String> list = new ArrayList<>();
//            List<User> userList = new ArrayList<>();
//            for (Object o : user2) {
//                list.add(o.toString());
//            }
//            for (String s : list) {
//                User user1 = objectMapper.readValue(s, User.class);
//                userList.add(user1);
//            }
//            userMapper.deleteBatchIds(Collections.singletonList(userList.get(0).getId()));
//            System.out.println(userList);
//            List<User> userList = str;
//            System.out.println(substring);
//            objectMapper.

//        }
//        System.out.println(user1);
//    }




//    @SuppressWarnings({"rawtypes"})
//    private void generateRequestHeader(RequestBuilder requestBuilder) {
//        boolean debugEnabled = LOGGER.isDebugEnabled();
//        Map<String, String> headerParamMap = new HashMap<>(16);
//        headerParamMap.put(HTTP.USER_AGENT, "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36");
//        headerParamMap.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3");
//        headerParamMap.put("Accept-Encoding", "gzip, deflate, br");
//        headerParamMap.put("Accept-Language", "zh-CN,zh;q=0.9");
//        headerParamMap.put("Cache-Control", "max-age=0");
//        headerParamMap.put("Connection", "keep-alive");
//        headerParamMap.put("Host", "api.jisuapi.com");
//        headerParamMap.put("Upgrade-Insecure-Requests", "1");
//        if(RootContext.inGlobalTransaction()) {
//            //http调用，传递xid到header,  TransactionPropagationInterceptor 接收绑定
//            headerParamMap.put("TX_XID", RootContext.getXID());
//        }
//        if (debugEnabled) {
//            LOGGER.debug("============>request header params begin<============");
//        }
//        for (Map.Entry<String, String> entry : headerParamMap.entrySet()) {
//            if (debugEnabled) {
//                LOGGER.debug("key=[{}], value=[{}].", entry.getKey(), entry.getValue());
//            }
//            if (!StringUtils.isEmpty(entry.getKey())) {
//                requestBuilder.setHeader(entry.getKey(), entry.getValue());
//            }
//        }
//        if (debugEnabled) {
//            LOGGER.debug("============>request header params end<============");
//        }
//    }
    /**
     * 根据 requestData 生成 请求参数信息
     *
     * @param requestBuilder
     */
//    @SuppressWarnings({"unchecked", "rawtypes"})
//    private void generateRequestParam(RequestBuilder requestBuilder) {
//        Map<String, String> requestParamMap = new HashMap<>();
//        requestParamMap.put("appkey","62958a3a6ef3c56d");
//        requestParamMap.put("question","石阡天气");
//        if (!CollectionUtils.isEmpty(requestParamMap)) {
//            LOGGER.debug("============>request params begin<============");
//            requestParamMap.forEach((k, v) -> {
//                requestBuilder.addParameter(k, v);
//                LOGGER.debug("key=[{}], value=[{}].", k, v);
//            });
//            LOGGER.debug("============>request params end<============");
//        }
//    }

}
